import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get_storage/get_storage.dart';
import 'package:jxchmz/%E4%BB%93%E7%AE%A1/%E7%89%A9%E8%B5%84%E5%85%A5%E5%BA%93/NotesXiangQing.dart';
import 'package:jxchmz/%E4%BB%93%E7%AE%A1/%E7%89%A9%E8%B5%84%E5%87%BA%E5%BA%93/OutNotesXiangQing.dart';
import 'package:jxchmz/API/%E5%BA%93%E5%AD%98%E7%AE%A1%E7%90%86/KuCunManager.dart';
import 'package:jxchmz/Getx%E5%B7%A5%E5%85%B7/GetxTools.dart';
import 'package:jxchmz/Getx%E5%B7%A5%E5%85%B7/KSProgressDialog.dart';
import 'package:get/get.dart';
class OutNotes extends StatefulWidget {
  @override
  _OutNotesState createState() => new _OutNotesState();
}

class _OutNotesState extends State<OutNotes> {
  TextEditingController SearchController = new TextEditingController();
  String date = "";
  //年
  String Year = "";
  //月
  String Month = "";
//订单列表
  List OrderList = [];

  // 当前页数
  int _page = 1;

  // 是否还有
  bool _hasMore = true;

  // 滚动控制器
  ScrollController _scrollController = new ScrollController();
  //入库类型数组
  List<PopupMenuItem<String>> TypeList= [];
  List TypeChild = [{"id":"0","name":"销售出库"},{"id":"1","name":"采购退货出库"},];
  var TypeId = "0" ;
  var TypeName = "销售出库";
//页面加载完成时
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    date = DateTime.now().toString().substring(0, 7);
    Year = DateTime.now().toString().substring(0, 4);
    Month = DateTime.now().toString().substring(5, 7);
    // 监听滚动事件
    _scrollController.addListener(() {
      var maxScroll = _scrollController.position.maxScrollExtent;
      var pixel = _scrollController.position.pixels;
      if (maxScroll == pixel) {
        if (_hasMore) {
          _page++;
          GetlistSaleOrder();
        }
      }
    });
    Future.delayed(Duration.zero,(){
      TypeChild.forEach((element) {
        TypeList.add(
            PopupMenuItem(
              child: SizedBox(
                width: MediaQuery.of(context).size.width-100,
                child: Text(element['name']),
              ),
              value: element['id'],
            )
        );
      });
      GetlistSaleOrder();
    });
    setState(() {});
  }

  ///页面卸载
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  ///当 State 被暂时从视图树中移除时，会调用这个方法，同时页面切换时，也会调用。
  @override
  void deactivate() {
    // TODO: implement dispose
    super.deactivate();
  }

  ///在 initState() 之后调用，当 State 对象的依赖关系发生变化时，该方法被调用，初始化时也会调用。
  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    super.didChangeDependencies();
  }

  // TODO: add state variables and methods
  @override
  Widget build(BuildContext context) {
    // TODO: add widget build method
    return Scaffold(
      backgroundColor: Colors.white,
        appBar: AppBar(
          backgroundColor: Colors.white,
          title: CupertinoSearchTextField(
            controller: SearchController,
            placeholder: "Ordernumber".tr,
            placeholderStyle: TextStyle(fontSize: 13, color: Colors.black38),
          ),
          centerTitle: true,
          elevation: 0,
          iconTheme: IconThemeData(color: Colors.black),
          actions: [
            TextButton(
                onPressed: () {
                  //搜索事件
                  SearchOrder();
                },
                child: Text(
                  "Search".tr,
                  style: TextStyle(color: Colors.black),
                ))
          ],
        ),
        body: Container(
            padding: EdgeInsets.only(left: 15, right: 15),
            child: Column(
              children: [
                Row(
                  children: [
                    //选择日期
                    Container(
                      child: TextButton(
                        child: Row(
                          children: [
                            Text(
                              date.isEmpty ? "Selectadate".tr : date,
                              style: TextStyle(color: Colors.black),
                            ),
                            Icon(
                              Icons.arrow_drop_down,
                              color: Colors.black,
                            )
                          ],
                        ),
                        onPressed: () {
                          showdata(context);
                        },
                      ),
                    ),
                    //选择入库类型
                    PopupMeunType(),
                  ],
                ),
                Expanded(
                  child: ListView.separated(
                    itemCount: OrderList.length,
                    controller: _scrollController,
                    itemBuilder: (context, index) {
                      return ListTile(
                        title: Column(
                          children: [
                            Row(
                              children: [
                                Container(
                                  child: Text(
                                    "Ordernumber".tr+":${OrderList[index]['billNo']}",
                                    style: TextStyle(fontSize: 13),
                                  ),
                                ),
                                Container(
                                  child: Text("${OrderList[index]['billDate']}", style: TextStyle(fontSize: 13, color: Colors.black38)),
                                ),
                              ],
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            ),
                            // Container(
                            //   height: 5,
                            // ),
                            // Row(
                            //   mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            //   children: [
                            //    TypeId==1?Container(
                            //       child: Text("Outboundquantity".tr+":${OrderList[index]['outQty'].toInt().toString()}", style: TextStyle(fontSize: 13)),
                            //     ):Container(),
                            //     Container(
                            //       child: Text("Thenumberofreturns".tr+":${OrderList[index]['settleQty']}", style: TextStyle(fontSize: 13)),
                            //     )
                            //   ],
                            // ),
                            Container(
                              height: 5,
                            ),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Container(
                                  child: Text("Thenumberofplannedshipments".tr+":${OrderList[index]['planAlreadyOutboundNumber']}", style: TextStyle(fontSize: 13)),
                                ),
                                Container(
                                  child: Text("Thenumberofshipmentsthathavebeenshipped".tr+":${OrderList[index]['alreadyOutboundNumber']}", style: TextStyle(fontSize: 13)),
                                ),

                              ],
                            ),
                            Container(
                              height: 5,
                            ),
                            Container(
                              child: TypeId=="0"?Text("SalOrderNum".tr+":${OrderList[index]['jxcSalOrderBillNo']}", style: TextStyle(fontSize: 13)):Text("PrfOrderNum".tr+":${OrderList[index]['prfOrderBillNo']}", style: TextStyle(fontSize: 13)),
                              alignment: Alignment.centerLeft,
                            ),
                            Container(
                              height: 5,
                            ),
                            Row(
                              children: [
                                Container(
                                  child: Text(
                                    "1",
                                    style: TextStyle(color: Colors.white),
                                  ),
                                ),
                                Container(
                                  child: MaterialButton(
                                    shape: const RoundedRectangleBorder(
                                      //边框圆角
                                      borderRadius: BorderRadius.all(
                                        Radius.circular(15),
                                      ),
                                    ),
                                    child: Text(
                                      "detail".tr,
                                      style: TextStyle(color: Colors.white, fontSize: 13),
                                    ),
                                    onPressed: () {
                                      //进入详情
                                      Get.to(OutNotesXiangQing(),arguments: {"Data":OrderList[index]});
                                    },
                                    color: Colors.blue,
                                  ),
                                  width: 60,
                                  height: 25,
                                  alignment: Alignment.centerRight,
                                ),
                              ],
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            )
                          ],
                        ),
                      );
                    },
                    separatorBuilder: (context, index) {
                      return Divider();
                    },
                  ),
                )
              ],
            ))
    );
  }
  //弹窗选择日期
  showdata(context) async {
    GetStorage storage = new GetStorage();
    var Language = json.decode(await storage.read("Langage"));
    print("语言:$Language");
    List CodeList = [];
    CodeList = Language['LangageCode'].split("-");
    DateTime? SelectDate =
    await showDatePicker(context: context, initialDate: DateTime.now(), lastDate: DateTime.now(), firstDate: DateTime(1900, 01, 01),locale:  Locale(CodeList[0], CodeList[1]));
    date = SelectDate.toString().substring(0, 7);
    Year = date.substring(0,4);
    Month = date.substring(5,7);
    //获取销售订单
    SearchOrder();
    setState(() {});
  }
  //弹出菜单筛选入库类型
  Widget PopupMeunType(){
    return PopupMenuButton<String>(
      onSelected: (value) {
        print("选择的物资数据:$value");
        TypeId = value;
        TypeChild.forEach((item) {
          if(item['id']==value){
            TypeName = item['name'];
          }
        });
        _page = 1;
        _hasMore = true;
        SearchOrder();
        setState(() {
        });
      },
      child: Row(
        children: [
          Text(TypeId==null?'Selecttheitem'.tr:TypeName),
          Icon(Icons.arrow_drop_down)
        ],
      ),
      itemBuilder: (context) {
        return TypeList;
      },
    );

  }
  //获取销售订单
  GetlistSaleOrder() async {

    //取出本地个人信息
    GetStorage getStorage = new GetStorage();
    var Userid = json.decode(getStorage.read("User"))['user']['userId'];
    int permissions = getStorage.read("permissions");
    var data;
    //搜索参数
    if(permissions==2){
      data = {
        "pageNum": _page,
        "pageSize": 10,
        "reasonable": false,
        "stockIoType": 1,
        "appYear":Year,
        "app_month":Month,
        "isRubric":int.parse(TypeId)
      };
    }else{
      data = {
        "pageNum": _page,
        "pageSize": 10,
        "reasonable": false,
        "operator":Userid,
        "stockIoType": 1,
        "appYear":Year,
        "app_month":Month,
        "isRubric":int.parse(TypeId)
      };
    }
    KSProgressDialog().LoadingToast("Loading".tr, context);
    var ResponseData = await KuCunManager().GetEntryAndOutOrder(data);
    KSProgressDialog().CloseLoading();
    if (ResponseData['code'] == 200) {
      var List = ResponseData['rows'];
      if (List.length <= 0) {
        // 关闭加载
        this._hasMore = false;
      } else {
        List.forEach((element) {
          OrderList.add(element);
        });
      }
    } else {
      new GetxTools().ErrorToast("Failedtogetsalesorderinformation".tr);
    }
    setState(() {});
  }
  //搜索事件
  SearchOrder() {
    _page = 1;
    _hasMore = true;
    OrderList = [];
    GetlistSaleOrder();
  }
}
